'''
Author: didiplus
Date: 2022-12-05 10:05:48
LastEditors: didiplus
LastEditTime: 2022-12-05 15:37:30
Description: 
'''


import xlwt,os,re,time,paramiko
from xlwt import *


hostMaping = {
    "10.91.74.35":"_S5710(1)",
    "10.91.74.36":"_S5710(2)",
    "10.91.74.37":"_S5710(3)",
    "10.91.74.38":"_S5710(4)",
    "10.91.74.39":"_S5710(5)",
    "10.91.74.40":"_S5700"
}

def maphostname(hostip):
    return hostMaping[hostip]




def macth_res(rule,fileData):
    """
    param: rule规则
    param: fileData文件内容
    return: list
    扫描当前路径下的巡检日志
    """
    compile_name = re.compile(rule, re.M)
    res=compile_name.findall(fileData)
    if len(res) != 0:
       return res
    return None

def  scanFile(path):

    """
    param: path
    return: list
    扫描当前路径下的巡检日志
    """
    fileList = os.listdir(path)
    return [ filename for filename in fileList if filename.endswith(".txt") ]


def ReadFile():
    files=scanFile("./log")
    all_data=[]
    for file in files:
        host= file.split("_")[0]
        data = {}
        f = open("./log/"+file)
        fileData = f.read()
        uptime = macth_res("uptime is(.*)",fileData)
        data["uptime"]=uptime[0]
        verson = macth_res("Software Version : (.*)",fileData)
        data['version'] =verson[0]
        power = macth_res("POWER (.*)",fileData)
        #提取电源状态信息
        if power is not None:
            for i,j in enumerate(power):
                data["power"+str(i)]=j.strip().split(" ")[10]

        cpuUsage = macth_res("CPU Usage            :(.*)",fileData)
        data["cpuUsage"] =cpuUsage[0]
        fan = macth_res("Fan(.*)",fileData)
        #提取风扇状态信息
        if fan is not None:
            for i,j in enumerate(fan):
                data["fan"+str(i)]=j.strip().split(" ")[-1].replace(".","")       
        memoryUsingPer=macth_res("Memory Using Percentage Is:(.*)",fileData)
        data["memoryUsingPer"]=memoryUsingPer[0]
        all_data.append({host:data})
    return all_data

def formatData(data):
    dataList=[]
    for item in data:
        for k,v in item.items():
            for i,j in v.items():
                dataList.append((maphostname(k),k,i,j))
    return dataList


def saveInfoToEexecl(data):
    #创建一个工作簿workbook
    workbook = xlwt.Workbook(encoding='utf-8')
    partial_style = XFStyle()
    borders = xlwt.Borders()
    borders.left = 1
    borders.right = 1
    borders.top = 1
    borders.bottom = 1
    partial_style.borders = borders
    pattern = xlwt.Pattern()
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    pattern.pattern_fore_colour = 5
    partial_style.pattern = pattern
    al = xlwt.Alignment()
    al.horz = 0x02
    al.vert = 0x01
    partial_style.alignment =al
 
    # 创建一个sheet对象,第二个参数是指单元格是否允许重设置，默认为False
    sheet = workbook.add_sheet('网络设备巡检', cell_overwrite_ok=True)
    #设置表头
    col_name = ("设备名称","管理地址", "检查项", "巡检结果")
    for i in range(len(col_name)):
        sheet.write(0,i,col_name[i],partial_style)

        
    for i in range(len(data)):
        In_data = data[i]
        for j in range(len(col_name)):
            if j == 0:
                pass
            sheet.write(i+1,j,In_data[j],)

    workbook.save("text.xls")


if __name__ == "__main__":
    
    data= ReadFile()

    saveInfoToEexecl(formatData(data))
   